package gather

import (
	"errors"
	"fmt"
	"gration/common"
	"gration/model"
	"strconv"
	"time"

	"github.com/jinzhu/gorm"

)

//一天获取一回

func SmookePop() {
	db := common.DB
	var base []model.BasicInfosTwo
	var suninfo []model.Summarys
	var cigar model.CigaretteInformationSummarys
	var smokecount int64
	var smoketotal float64
	db.Table("basic_infos_twos").Find(&base)
	for _, bases := range base {
		er := db.Table("summarys").Where("cigar_code=? ", bases.CigarCode).Find(&suninfo).Error
		if errors.Is(er, gorm.ErrRecordNotFound) {
			//cigar.TimeDay=time.Now().Format("2006-01-02 15:04:05")
			fmt.Println(er)
		} else {
			for _, suminfo := range suninfo {
				smokecountint, _ := strconv.ParseInt(suminfo.SmokeCount, 0, 64)
				smokecount = smokecount + smokecountint
				smoketotalint, _ := strconv.ParseFloat(suminfo.SmokeTotalTime, 64)
				smoketotal = smoketotal + smoketotalint
			}
			fmt.Println(smoketotal)
			/*common.CountDB.Table("cigarette_information_summarys").Where("cigar_code=? ", bases.CigarCode).
			Updates(map[string]interface{}{
				"smoke_pop":           suninfo.SmokeCount,                                       //更新IP
				"smoke_duration":      suninfo.SmokeTotalTime, //
				})                         //*/
		}
	}
	var cigequ []model.BasicInfosTwo
	db.Table("basic_infos_twos").Find(&cigequ) //获取00表数据
	var SmokingInfos []model.SmokingInfosTwo   //02表数据
	var daytime []string
	newusers := 0 //初始化新老用户人数
	oldusers := 0
	for i, n := 0, len(cigequ); i < n; i++ {
		db.Table("smoking_infos_two").Where("cigar_code = ?", cigequ[i].CigarCode).Find(&SmokingInfos)
		for j, m := 0, len(SmokingInfos); j < m; j++ {
			daytime = append(daytime, SmokingInfos[j].SmokeTime[0:10]) //时间格式 2022-2-28
		}
		daytime = RemoveRepeatedElement(daytime) //时间去重
		if len(daytime) >= 10 {
			oldusers++
		} else {
			newusers++
		}
	}
	timeNow := time.Now().Format("2006-01-02")
	err1 := common.CountDB.Table("cigarette_information_summarys").Where("time_day = ?",timeNow).
		Find(&cigar).Error
	cigar.NewPeople = int64(newusers)
	cigar.OldPeople = int64(oldusers)
	cigar.TimeDay = timeNow
	cigar.SmokePop = smokecount
	cigar.SmokeDuration = smoketotal
	if errors.Is(err1, gorm.ErrRecordNotFound) {
		fmt.Println(err1)
		common.CountDB.Table("cigarette_information_summarys").Create(&cigar)
	}else {
		common.CountDB.Table("cigarette_information_summarys").Where("time_day = ?",
			timeNow).Updates(map[string]interface{}{
			"new_people": cigar.NewPeople,
			"old_people": cigar.OldPeople,
			"smoke_pop" : cigar.SmokePop ,
			"smoke_duration" : cigar.SmokeDuration,
		})
	}

	fmt.Println(cigar)
}

//时间切分

func TimeDrawing (){
	db := common.DB
	var turetime []model.FragMent
	//var index model.FragmentDrawing
	var base []model.BasicInfosTwo
	now :=time.Now().Format("2006-01-02")
	//now :="2022-03-04"
	tar :=now +" 00:00:00.000"
	end :=now +" 23:59:59.999"
	fmt.Println(tar)
	fmt.Println(end)
	//common.DB.Table("fragments").Where("star_time  BETWEEN ? AND ?",tar,end).Find(&turetime)
	fmt.Println(turetime)
	db.Table("basic_infos_twos").Find(&base)
	for _, bases := range base {

		er := db.Table("fragments").Where("cigar_code=? and start_time BETWEEN ? AND ?", bases.CigarCode,tar,end).Find(&turetime).Error
		if errors.Is(er, gorm.ErrRecordNotFound) {
			fmt.Println(er)
		} else {
			for _,ture:= range turetime{
				/*max, _ := strconv.ParseInt(ture.Max, 0, 64)
		
				invaule:=TimeStr2Time(ture.StarTime)
				nowstmes := time.Duration(max*800) * time.Millisecond
				nowstar := invaule.Add(-nowstmes)
		
				index.CigarCode=ture.CigarCode
				index.StarTime =nowstar.Format("2006-01-02 15:04:05.999")
				index.EndTime=ture.StarTime
				index.Max=ture.Max
				common.CountDB.Table("fragment_drawings").Create(&index)
				fmt.Println(ture.StarTime)*/
				nowstar:=TimeStr2Time(ture.StartTimeDrawing)
				SmookeDorwing(ture.StartTime,ture.EndTime,nowstar,bases.CigarCode)
			}
		}
 } 
}

func TimeStr2Time(timeStr string) time.Time {
    var layout = "2006-01-02 15:04:05.999" //转换的时间字符串带秒则 为 2006-01-02 15:04:05
    timeVal, errByTimeConver := time.ParseInLocation(layout, timeStr, time.Local)
    if errByTimeConver != nil {
        fmt.Println("TimeStr To Time Error.....", errByTimeConver)
    }
    return timeVal
  }


func SmookeDorwing(startime,endtime string,turetime time.Time,code string) {
	db := common.DB
	var Dowings []model.Details
	var smoked model.SmookeDrawings
		er := db.Table("details").Where("cigar_code=? and time_data BETWEEN ? AND ?", code,startime,endtime).Find(&Dowings).Error
		if errors.Is(er, gorm.ErrRecordNotFound) {
			fmt.Println(er)
		} else {
			fmt.Println(len(Dowings))
			for i, dowe := range Dowings {
				nowstmes := time.Duration(i*10) * time.Millisecond
				nowstar := turetime.Add(nowstmes)

				smoked.CigarCode = code
				smoked.Siganl0 = strconv.FormatInt(dowe.D00, 10)
				smoked.Siganl1 = strconv.FormatInt(dowe.D01, 10)
				smoked.Siganl2 = strconv.FormatInt(dowe.D02, 10)
				smoked.Siganl3 = strconv.FormatInt(dowe.D03, 10)
				smoked.Siganl4 = strconv.FormatInt(dowe.D04, 10)
				smoked.Siganl5 = strconv.FormatInt(dowe.D05, 10)
				smoked.Siganl6 = strconv.FormatInt(dowe.D06, 10)
				smoked.Siganl7 = strconv.FormatInt(dowe.D07, 10)
				smoked.Counts = strconv.FormatInt(dowe.D2, 10)
				smoked.ValueR = strconv.FormatInt(dowe.D3_4, 10)
				smoked.StableValuer = strconv.FormatInt(dowe.D5, 10)
				smoked.StarValuer = strconv.FormatInt(dowe.D6_7, 10)
				smoked.EndValuer = strconv.FormatInt(dowe.D8, 10)
				smoked.ThresholdValueCount = strconv.FormatInt(dowe.D9, 10)
				smoked.Group = dowe.Group
				smoked.TimeData = nowstar.Format("2006-01-02 15:04:05.999")
				smoked.FragMent = dowe.FragMent
				smoked.MmTime = nowstar.String()[20:23]
				common.CountDB.Table("smooke_drawings").Create(&smoked)
			}
			fmt.Println("处理完成")
		}
	

}

/*=========================================================
 * 函数名称： GetNetworkingNumber
 * 功能描述:  获取新老用户，绘图数据，一天统计一次
 =========================================================*/

//var cigequ []model.BasicInfosTwo
//db.Table("basic_infos_twos").Find(&cigequ) //获取00表数据
func GetNetworkingNumber() {
	db := common.DB
	var cigequ []model.BasicInfosTwo
	db.Table("basic_infos_twos").Find(&cigequ) //获取00表数据
	time_now := time.Now().Format("2006-01-02 15:04:05")[0:10]
	var SmokingInfos []model.SmokingInfosTwo //02表数据
	var daytime []string
	newusers := 0 //初始化新老用户人数
	oldusers := 0
	for i, n := 0, len(cigequ); i < n; i++ {
		db.Table("smoking_infos_two").Where("cigar_code = ?", cigequ[i].CigarCode).Find(&SmokingInfos)
		for j, m := 0, len(SmokingInfos); j < m; j++ {
			daytime = append(daytime, SmokingInfos[j].SmokeTime[0:10]) //时间格式 2022-2-28
		}
		daytime = RemoveRepeatedElement(daytime) //时间去重
		if len(daytime) >= 10 {
			oldusers++
		} else {
			newusers++
		}
	}
	//###################################net_drawing曲线#################################
	var net_stat []model.NetDrawing
	var net_stat_new [1]model.NetDrawing
	time_yesterday := time.Now().Add(-time.Duration(24) * time.Hour).Format("2006-01-02 15:04:05")[0:10]
	//查找昨日信息，若没有则将今日数据写入

	/* common.CountDB.Table("net_drawing").Where("data_time = ?",time_yesterday).FirstOrCreate(&net_stat,
	model.NetDrawing{DateTime:time_now,NetWorking:oldusers + newusers,MarginValue:oldusers + newusers})
	fmt.Println(time_now)*/
	er := common.CountDB.Table("net_drawing").Where("date_time= ? ", time_yesterday).Find(&model.NetDrawing{}).Error
	if errors.Is(er, gorm.ErrRecordNotFound) {
		use := model.NetDrawing{
			DateTime:    time_now,
			NetWorking:  oldusers + newusers,
			MarginValue: oldusers + newusers,
		}
		common.CountDB.Table("net_drawing").Create(&use)
	} else {

		fmt.Println(time_yesterday)
		common.CountDB.Table("net_drawing").Where("date_time= ? ", time_yesterday).Find(&net_stat)
		fmt.Println(net_stat)
		if net_stat[0].DateTime != time_now {
			net_stat_new[0].DateTime = time_now                                               //今日时间
			net_stat_new[0].NetWorking = oldusers + newusers                                  //今日联网量
			net_stat_new[0].MarginValue = net_stat_new[0].NetWorking - net_stat[0].NetWorking //今日较昨日的联网差值
			common.CountDB.Table("net_drawing").Create(net_stat_new[0])

		}
	}
}

/*=========================================================
 * 函数名称： RemoveRepeatedElement
 * 功能描述:  切片去重
 =========================================================*/
func RemoveRepeatedElement(s []string) []string {
	result := make([]string, 0)
	m := make(map[string]bool) //map的值不重要
	for _, v := range s {
		if _, ok := m[v]; !ok {
			result = append(result, v)
			m[v] = true
		}
	}
	return result
}

/*=========================================================
 * 函数名称：SmokePowerOneDay(yesterday string)
 * 功能描述: 计算昨天24小时每个小时的平均吸抽功率，存储到数据库
 * 输出指标: 以yyyy-mm-dd hh:mm:ss的形式输出时间字符串切片
 =========================================================*/
func SmokePowerOneDay( db *gorm.DB,ch chan []model.SmokingInfosTwo) {
	for{
		info := <- ch
		fmt.Println("每四秒通道传进来的数据：",info)
		//timeNow:=time.Now().Format("2006-01-02")
		//timeNowstart := timeNow + "00:00:00"
		//timeNowend := timeNow + "23:59:59"
		time_start,time_end := SplitHours()
		fmt.Println("开始的时间",time_start)
		fmt.Println("结束的时间",time_end)
		fmt.Println("总共的新数据:",len(info))
		type HeatPowerStruct struct {
			AvgHeatPower float64
		}
		var oldsmokingpower model.SmokingPowers
		var AvgHeatPower HeatPowerStruct
		db.Table("smoking_infos_two").Select("AVG(heat_power) avg_heat_power").
			Where("handle_flag = ? AND smoke_time between ? and ?",0,time_start,time_end).
			Scan(&AvgHeatPower)
		db.Table("smoking_infos_two").Where("handle_flag = ? AND smoke_time between ? and ?",0,time_start,time_end).
			Updates(map[string]interface{}{
				"handle_flag" : 1,
			})
		err1 := common.CountDB.Table("smoking_powers").Where("time_hours = ?",time_start).
			Find(&oldsmokingpower).Error
		if errors.Is(err1, gorm.ErrRecordNotFound) {
			fmt.Println("第一次查询平均功率没有数据")
            firstpower := model.SmokingPowers{
				TimeHours:time_start,
				NewSmokingPower : AvgHeatPower.AvgHeatPower,
			}
			common.CountDB.Table("smoking_powers").Create(&firstpower)
		}else {
			fmt.Println("第一次查询平均功率有数据")
			AvgPowers := (oldsmokingpower.NewSmokingPower + AvgHeatPower.AvgHeatPower)/2
			common.CountDB.Table("smoking_powers").Where("time_hours = ?",time_start).Updates(map[string]interface{}{
				"new_smoking_power" : AvgPowers,
			})
		}

	}
	//now := time.Now()
	//yesterday := now.AddDate(0, 0, -1).Format("2006-01-02")
	//fmt.Println(yesterday)
	////获取24个小时
	//hours := SplitHours(yesterday)
	//fmt.Println(hours)
	//
	//for i := 0; i <= 23; i++ {
	//	firstHour := hours[i]
	//	var SecondHour string
	//	if i == 23 {
	//		SecondHour = yesterday + " 24:00:00"
	//	} else {
	//		SecondHour = hours[i+1]
	//	}
	//	type HeatPowerStruct struct {
	//		AvgHeatPower float64
	//	}
	//	var HeatPower HeatPowerStruct
	//	common.DB.Table("smoking_infos_two").Select("AVG(heat_power) avg_heat_power").
	//		Where("smoke_time BETWEEN ? AND ?", firstHour, SecondHour).Scan(&HeatPower)
	//	fmt.Printf("%s吸抽功率为%f\n", SecondHour, HeatPower.AvgHeatPower)
	//	//存储到数据库
	//	var SmokingPower model.SmokingPowers
	//	if i == 23 {
	//		SmokingPower.TimeHours = hours[0]
	//	} else {
	//		SmokingPower.TimeHours = hours[i+1]
	//	}
	//	SmokingPower.NewSmokingPower = HeatPower.AvgHeatPower
	//	common.CountDB.Model(&model.SmokingPowers{}).Create(&SmokingPower)
	}


/*=========================================================
 * 函数名称：SplitHours(yesterday string)
 * 功能描述: 将昨天划分为24个小时
 * 输出指标: 以yyyy-mm-dd hh:mm:ss的形式输出时间字符串切片
 =========================================================*/
func SplitHours() (string ,string) {
	time_now := time.Now().Format("2006-01-02 15:04:05")
	time_end := time.Now().Add(1*time.Hour).Format("2006-01-02 15:04:05")
	time_start := time_now[0:13]+":00:00"
	time_end = time_end[0:13]+":00:00"
	return time_start ,time_end
}
